/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fametro.model.dao;

import br.com.fametro.model.bean.Bairro;
import br.com.fametro.model.connection.ConnectionFactory;
import java.util.*;
import javax.swing.*;
import org.hibernate.*;

/**
 *
 * @author Daniel
 */
public class BairroDao {
    
    Session session;
    Transaction transaction;
    List<Bairro> listaBairro = new ArrayList<Bairro>();
    
    
    public void salvar(Bairro bairro){
        
        try{
            session = new ConnectionFactory().getSessionFactory();
            transaction = session.beginTransaction();
            session.save(bairro);
            transaction.commit();
            session.close();
                    
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, ""+e.getMessage());
            transaction.rollback();
            session.close();
        }
    }
    
    public void alterar(Bairro bairro){
        
        try{
            session = new ConnectionFactory().getSessionFactory();
            transaction = session.beginTransaction();
            session.update(bairro);
            transaction.commit();
            session.close();
                    
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, ""+e.getMessage());
            transaction.rollback();
            session.close();
        }
    }
    
    public Bairro consultarbairro(String nome){
        session = new ConnectionFactory().getSessionFactory();
        Query query = session.createSQLQuery("SELECT * FROM bairro where descr_bairro = '"+nome+"'").addEntity(Bairro.class);
        System.out.println("SELECT * FROM bairro where descr_bairro = '"+nome+"'");
        listaBairro = query.list();
        return listaBairro.get(0);
           
    }
    
    
    
    public List<Bairro> listar(){
        session = new ConnectionFactory().getSessionFactory();
        listaBairro = session.createCriteria(Bairro.class).list();
       return listaBairro;
       
        
    }
    
    public void excluir (Bairro bairro){
       try{
           
       
        session = new ConnectionFactory().getSessionFactory();
            transaction = session.beginTransaction();
            session.delete(bairro);
             transaction.commit();
            session.close();

       }catch(Exception e ){
           JOptionPane.showMessageDialog(null, ""+e.getMessage());
            transaction.rollback();
            session.close();
           
       }     
        
    }
    
}
